package com.xyz.mycamera.camera;

import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.view.SurfaceView;
import android.view.View;


public class CameraSurfaceView extends SurfaceView {

    private CameraHelper cameraHelper;
    private int cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;

    public CameraSurfaceView(Context context) {
        this(context, null);
    }

    public CameraSurfaceView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CameraSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        cameraHelper = new CameraHelper(context);
        setOnClickListener(v -> {
            if (cameraHelper != null) {
                cameraHelper.autoFocus();
            }
        });
        post(() -> {
            if (cameraHelper != null) {
                cameraHelper.autoFocus();
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = View.MeasureSpec.getSize(widthMeasureSpec);
        int height = View.MeasureSpec.getSize(heightMeasureSpec);
        cameraHelper.setScreenW(width);
        cameraHelper.setScreenH(height);
    }

    public void startCamera() {
        post(() -> {
            cameraHelper.startCamera(getHolder(), cameraId);
        });
    }

    public void switchCamera() {
        if (isBackCamera()) {
            cameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
        } else {
            cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
        }
        cameraHelper.switchCamera(cameraId);
    }

    public boolean isBackCamera() {
        return cameraId == Camera.CameraInfo.CAMERA_FACING_BACK;
    }

    public void onDestroy() {
        if (cameraHelper != null) {
            cameraHelper.stopPreview();
        }
    }
}
